package com.shareach.search.service;

import org.codehaus.jackson.type.TypeReference;

import com.shareach.basic.HttpBase;
import com.shareach.basic.ServiceException;
import com.shareach.domain.Location;
import com.shareach.search.baidu.domain.Content;
import com.shareach.search.baidu.domain.Places;
import com.shareach.util.JsonUtil;
import com.shareach.util.URLEncodeUtils;
import com.shareach.web.basic.Answer;


public class BaiduSearcher extends HttpBase {
	private String host;
	public BaiduSearcher(String host){
		this.host = host;
	}

	/**
	 * @param city 城市名称，必须
	 * @param keyword 查询的关键词，必须进行URLencode，必须。
	 * @param center 中心点坐标，可以为空
	 * @param count 单页返回的记录条数，默认为20，最大为50。
	 */
	public Places search(String city, String keyword, Location center, Integer radius){
		StringBuffer sb = new StringBuffer();
		sb.append(host+"/baidu/search.do?city="+URLEncodeUtils.encodeURL(city));
		sb.append("&keyword="+URLEncodeUtils.encodeURL(keyword));
		if(center!=null){
			sb.append("&lat="+center.lat);
			sb.append("&lng="+center.lng);
		}
		if(radius!=null)sb.append("&radius="+radius);
		String json = this.httpGet(sb.toString(),null);
		try{
			Answer<Places> jsonResult =JsonUtil.objectFromJson(json, new TypeReference<Answer<Places>>(){});
			if(jsonResult.getCode()==0){
				return jsonResult.getResult();
			}else{
				return null;
			}
		}catch(Exception exp){
			throw new ServiceException(-1,"百度Api搜索错误："+exp.getMessage());
		}
	}
	
	/**
	 * 获取百度详细信息
	 * @param baiduId
	 * @return
	 */
	public Content get(String baiduId){
		StringBuffer sb = new StringBuffer();
		sb.append(host+"/baidu/get.do?id="+baiduId);
		String json =  this.httpGet(sb.toString(),null);
		try{
			Answer<Content> jsonResult =JsonUtil.objectFromJson(json, new TypeReference<Answer<Content>>(){});
			if(jsonResult.getCode()==0){
				return jsonResult.getResult();
			}else{
				return null;
			}
		}catch(Exception exp){
			throw new ServiceException(-1,"获取百度详细信息错误："+exp.getMessage());
		}
	}
}
